//
//  HttpRequestManager.mm
//  WisdomZhuHai
//
//  Created by Admin on 13-9-12.
//  Copyright (c) 2013年 wyd. All rights reserved.
//

#import "HttpRequestManager.h"
#import "ASINetworkQueue.h"
#import "ASIDownloadCache.h"
#import "AppDelegate.h"
#import "ASIFormDataRequest.h"
#import "Common.h"

@interface HttpRequestManager ()

@property (nonatomic,retain) NSMutableDictionary* queueDic;


@end

@implementation HttpRequestManager

@synthesize queueDic;

HttpRequestManager* sharedHttpRequestManager = nil;
int timeOut = 30;
int curQueueId = 0;

- (id)init
{
    self = [super init];
    if (self) {
        [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
        queueDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [self removeAllHttpRequestQueue];
    self.queueDic = nil;
    [super dealloc];
}

- (int)createHttpRequestQueue:(id<HttpRequestDelegate>)delegate
{
    curQueueId++;
    ASINetworkQueue* queue = [[ASINetworkQueue alloc] init];
    queue.delegate = self;
    queue.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:delegate, @"delegate", [NSNumber numberWithInt:curQueueId], @"id", nil];
    queue.requestDidFinishSelector = @selector(requestDidFinish:);
    queue.requestDidFailSelector = @selector(requestDidFail:);
    queue.queueDidFinishSelector = @selector(queueDidFinish:);
    queue.shouldCancelAllRequestsOnFailure = NO;
    [queueDic setObject:queue forKey:[NSNumber numberWithInt:curQueueId]];
    [queue release];
    return curQueueId;
}

- (BOOL)ifQueueUsable:(int)queueId
{
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];
    if (!networkQueue) {
        return NO;
    }
    else {
        return YES;
    }
}

- (BOOL)setSuspended:(BOOL)flag ForQueue:(int)queueId; //获取实例
{
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];   //声明并初始化网络队列
    if (!networkQueue) {    //如果网络队列为false，返回false
        return NO;
    }
    [networkQueue setSuspended:flag];   //flag:YES暂停队列，NO启动队列，并返回yes
    return YES;
}

- (BOOL)removeHttpRequestQueue:(int)queueId
{
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];
    if (!networkQueue) {
        return NO;
    }
    [networkQueue cancelAllOperations];
    [queueDic removeObjectForKey:[NSNumber numberWithInt:queueId]];
    return YES;
}

- (void)removeAllHttpRequestQueue
{
    NSEnumerator *enumerator = [queueDic objectEnumerator];
    id obj;
    while ((obj = [enumerator nextObject]))
    {
        ASINetworkQueue* queue = (ASINetworkQueue*)obj;
        [queue cancelAllOperations];
    }
    [queueDic removeAllObjects];
}

- (BOOL)addHttpRequestToQueue:(int)queueId Url:(NSURL*)url ToPath:(NSString*)path UserInfo:(NSDictionary*)dic Delegate:(id<HttpRequestDelegate>)delegate;
{
    [Common checkNetReachable];
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];
    if (!networkQueue) {
        return NO;
    }
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    request.downloadDestinationPath = path;
    request.delegate = delegate;
    request.didFinishSelector = @selector(requestDidFinish:);
    request.didFailSelector = @selector(requestDidFail:);
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [networkQueue addOperation:request];
    
    if ([[networkQueue operations] count] > 0) {
        [networkQueue go];
    }
    [request release];
    return YES;
}

- (BOOL)removeHttpRequestFromQueue:(int)queueId UserInfo:(NSDictionary*)dic
{
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];
    if (!networkQueue) {
        return NO;
    }
    if (dic == nil) {
        return YES;
    }
    for (ASIHTTPRequest* request in [networkQueue operations]) {
        if ([dic isEqual:request.userInfo]) {
            [request cancel];
        }
    }
    return YES;
}

- (void)startHttpDownloadTaskImmediately:(NSURL*)url ToPath:(NSString*)path withUserInfo:(NSDictionary*)dic Delegate:(id<HttpRequestDelegate>)delegate
{
    [Common checkNetReachable];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    request.downloadDestinationPath = path;
    request.delegate = delegate;
    request.didFinishSelector = @selector(requestDidFinish:);
    request.didFailSelector = @selector(requestDidFail:);
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [request startAsynchronous];
    [request release];
}

- (void)getHttpInfo:(NSURL*)url withUserInfo:(NSDictionary*)dic Delegate:(id<HttpRequestDelegate>)delegate
{
    [Common checkNetReachable];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    request.delegate = delegate;
    request.didFinishSelector = @selector(requestDidFinish:);
    request.didFailSelector = @selector(requestDidFail:);
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [request startAsynchronous];
    [request release];
}

- (BOOL)addHttpRequestToQueue:(int)queueId Url:(NSURL*)url ToPath:(NSString*)path UserInfo:(NSDictionary*)dic success:(ASIRequestSuccessBlock)success failure:(ASIRequestFailureBlock)failure
{
    [Common checkNetReachable];
    ASINetworkQueue *networkQueue = [queueDic objectForKey:[NSNumber numberWithInt:queueId]];
    if (!networkQueue) {
        return NO;
    }
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    request.downloadDestinationPath = path;
    [request setRequestSuccessBlock:success];
    [request setRequestFailureBlock:failure];
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [networkQueue addOperation:request];
    
    if ([[networkQueue operations] count] > 0) {
        [networkQueue go];
    }
    [request release];
    return YES;

}

- (void)startHttpDownloadTaskImmediately:(NSURL*)url ToPath:(NSString*)path withUserInfo:(NSDictionary*)dic success:(ASIRequestSuccessBlock)success failure:(ASIRequestFailureBlock)failure
{
    [Common checkNetReachable];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    request.downloadDestinationPath = path;
    [request setRequestSuccessBlock:success];
    [request setRequestFailureBlock:failure];
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [request startAsynchronous];
    [request release];
}

- (void)getHttpInfo:(NSURL*)url withUserInfo:(NSDictionary*)dic success:(ASIRequestSuccessBlock)success failure:(ASIRequestFailureBlock)failure
{
    [Common checkNetReachable];
    NSLog(@"%s || getHttpInfo %@", __FUNCTION__, url.absoluteString);
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.userInfo = dic;
    [request setRequestSuccessBlock:success];
    [request setRequestFailureBlock:failure];
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [request startAsynchronous];
    [request release];
}

- (void)getHttpInfo:(NSURL *)url postParams:(NSDictionary*)params success:(ASIRequestSuccessBlock)success failure:(ASIRequestFailureBlock)failure
{
    [Common checkNetReachable];
    NSLog(@"%s || getHttpInfo %@", __FUNCTION__, url.absoluteString);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
    for (NSString *key in params) {
        [request setPostValue:params[key] forKey:key];
    }
    [request setRequestSuccessBlock:success];
    [request setRequestFailureBlock:failure];
    request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
    request.cachePolicy = ASIFallbackToCacheIfLoadFailsCachePolicy|ASIAskServerIfModifiedCachePolicy;
    request.timeOutSeconds = timeOut;
    [request startAsynchronous];
//    [request startSynchronous];
    [request release];
}

- (void)requestDidFinish:(ASIHTTPRequest*)request
{
    NSLog(@"requestDidFinish");
}

- (void)requestDidFail:(ASIHTTPRequest*)request
{
    NSLog(@"requestDidFail");
}

- (void)queueDidFinish:(ASINetworkQueue*)queue
{
    NSLog(@"queueDidFinish");
    NSDictionary *userInfo = queue.userInfo;
    id<HttpRequestDelegate> delegate = [userInfo objectForKey:@"delegate"];
    if (delegate && [delegate respondsToSelector:@selector(queueDidFinish:)]){
        [delegate queueDidFinish:queue];
    }
    [queueDic removeObjectForKey:[userInfo objectForKey:@"id"]];
}

+ (NSString*)getCachePathByUrl:(NSURL*)url
{
    return [[ASIDownloadCache sharedCache] pathToCachedResponseDataForURL:url];
}

+ (void)ClearCache
{
    [ASIHTTPRequest clearSession];
    [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
}

+ (HttpRequestManager*)getSharedInstance
{
    if (sharedHttpRequestManager == nil) {
        sharedHttpRequestManager = [[HttpRequestManager alloc] init];
    }
    return sharedHttpRequestManager;
}

@end
